<template>
  <div class="layout">
  <div class="container">
    <!-- 连接状态 - 右上角 -->
    <div class="connection-status-corner" :class="{ connected: isConnected, disconnected: !isConnected }">
      <span class="status-dot"></span>
      <span class="status-text">{{ isConnected ? '已连接' : '未连接' }}</span>
    </div>

    <!-- 主要布局 -->
    <div class="main-layout">
      <!-- 左侧视频区域 -->
      <div class="left-panel">
        <div class="video-section">
          <div class="section-header">
            <h3>实时监控</h3>
            <div class="video-controls">
              <button class="video-control-btn" @click="toggleVideo" :class="{ active: isVideoEnabled }">
                <span>{{ isVideoEnabled ? '📹' : '📷' }}</span>
                <span>{{ isVideoEnabled ? '关闭' : '开启' }}</span>
              </button>
              <button class="video-control-btn" @click="refreshVideo" :disabled="!isVideoEnabled">🔄刷新</button>
            </div>
          </div>
          <div class="video-container">
            <div v-if="!isVideoEnabled" class="video-placeholder">
              <div class="placeholder-content">
                <p class="placeholder-text">点击开启查看视频流</p>
              </div>
            </div>
            <div v-else class="video-stream-wrapper">
              <img 
                :src="videoUrl" 
                alt="小车视频流" 
                class="video-stream"
                @load="onVideoLoad"
                @error="onVideoError"
                @click="toggleFullscreen"
                ref="videoElement"
              />
              <div v-if="videoError" class="video-error">
                <p>视频流加载失败</p>
                <button @click="refreshVideo" class="retry-btn">重试</button>
              </div>
              <div v-if="isVideoLoading" class="video-loading">
                <div class="loading-spinner"></div>
                <p>正在加载...</p>
              </div>
              <div class="video-info" v-if="!videoError && !isVideoLoading">
                <span class="video-status">🟢 实时</span>
                <span class="video-resolution">{{ videoResolution }}</span>
              </div>
            </div>
          </div>
        </div>
        <!-- 地图区域
        <div class="map-section-wrapper">
          <BaiduMap 
            ref="mapComponent"
            :latitude="vehicleLocation.latitude"
            :longitude="vehicleLocation.longitude"
            :api-config="API_CONFIG"
            @location-update="onLocationUpdate"
            @map-ready="onMapReady"
          />
        </div> -->
      </div>

      <!-- 右侧控制区域 -->
      <div class="right-panel">
        <!-- 方向控制轮盘 -->
        <div class="control-section joystick-section">
          <div class="section-header">
            <h3>方向控制</h3>
          </div>
          <div class="joystick-container">
            <div class="joystick-background">
              <div class="joystick-center"></div>
              <div 
                class="joystick-handle" 
                :style="{ transform: `translate(${joystickX}px, ${joystickY}px)` }"
                @mousedown="startDrag"
                @touchstart="startDrag"
              ></div>
              <div class="direction-indicators">
                <button class="indicator up" @click="sendCommand('car_control', { dir: 1 })">⬆️</button>
                <button class="indicator down" @click="sendCommand('car_control', { dir: 2 })">⬇️</button>
                <button class="indicator left" @click="sendCommand('car_control', { dir: 3 })">⬅️</button>
                <button class="indicator right" @click="sendCommand('car_control', { dir: 4 })">➡️</button>
              </div>
            </div>
            <div class="joystick-info">
              <span>X: {{ Math.round(joystickX) }} | Y: {{ Math.round(joystickY) }}</span>
            </div>
          </div>
        </div>

        <!-- 华为云IoT状态面板
        <div class="control-section iot-section">
          <div class="section-header">
            <h3>华为云IoT</h3>
            <button 
              class="iot-connect-btn" 
              @click="toggleIoTConnection"
              :class="{ connected: iotConnected, loading: iotLoading }"
              :disabled="iotLoading"
            >
              <span v-if="iotLoading" class="loading-icon">⏳</span>
              <span v-else-if="iotConnected" class="connected-icon">🟢</span>
              <span v-else class="disconnected-icon">🔴</span>
              {{ iotLoading ? '连接中...' : (iotConnected ? '已连接' : '未连接') }}
            </button>
          </div>
          
          <!-- IoT数据显示 -->
          <!-- <div class="iot-data" v-if="iotConnected && sensorData">
            <div class="sensor-grid">
              <div class="sensor-item">
                <span class="sensor-label">温度</span>
                <span class="sensor-value">{{ sensorData.temperature }}°C</span>
              </div>
              <div class="sensor-item">
                <span class="sensor-label">照度</span>
                <span class="sensor-value">{{ sensorData.illumination }} lux</span>
              </div>
              <div class="sensor-item">
                <span class="sensor-label">烟雾</span>
                <span class="sensor-value" :class="{ alert: sensorData.smoke }">
                  {{ sensorData.smoke ? '检测到' : '正常' }}
                </span>
              </div>
              <div class="sensor-item">
                <span class="sensor-label">PM2.5</span>
                <span class="sensor-value" :class="{ warning: sensorData.pm25 > 75, alert: sensorData.pm25 > 150 }">
                  {{ sensorData.pm25 }} μg/m³
                </span>
              </div>
            </div>
            <div class="iot-info">
              <small>更新时间: {{ formatTime(sensorData.eventTime) }}</small>
            </div>
          </div>
          
          <!-- 连接状态信息 -->
          <!-- <div class="iot-status" v-else-if="!iotConnected">
            <p class="status-message">点击连接按钮开始获取传感器数据</p>
          </div>
        </div>  -->

        <div class="control-section xycontrol-section">
            <!-- 速度控制 -->
            <div class="speed-control-group">
              <div class="speed-item">
                <label>X轴速度: <span class="speed-value">{{ xSpeed }}</span></label>
                <input type="range" min="-127" max="127" v-model.number="xSpeed" :disabled="!isConnected" class="speed-slider" />
              </div>
              <div class="speed-item">
                <label>Y轴速度: <span class="speed-value">{{ ySpeed }}</span></label>
                <input type="range" min="-127" max="127" v-model.number="ySpeed" :disabled="!isConnected" class="speed-slider" />
              </div>
              <button class="control-btn speed-send-btn" @click="sendCommand('speed_control', { x: xSpeed, y: ySpeed })" :disabled="!isConnected">发送速度</button>
            </div>
          </div>
      </div>
      
    </div>
    <div>
           <!-- 功能按钮集 -->
        <div class="control-section buttons-section">
          <div class="button-grid">
            <!-- 基础控制 -->
            <div class="button-group">
              <!-- 紧急停止按钮 - 最优先位置 -->
              <button class="control-btn emergency-btn" @click="emergencyReset()">
                <span>紧急重置</span>
              </button>
              <button class="control-btn" @click="sendCommand('car_control', { dir: 0 })" :disabled="!isConnected">
                <span>停车</span>
              </button>
              <button class="control-btn" @click="sendCommand('car_control', { dir: 7 })" :disabled="!isConnected">
                <span>刹车</span>
              </button>
              <button class="control-btn" @click="sendCommand('car_control', { dir: 5 })" :disabled="!isConnected">
                <span>左旋</span>
              </button>
              <button class="control-btn" @click="sendCommand('car_control', { dir: 6 })" :disabled="!isConnected">
                <span>右旋</span>
              </button>
              <button class="control-btn" @click="beepControl()">
                <span>短蜂鸣</span>
              </button>
              <!-- <button class="control-btn" @click="updateVehicleLocation()">
                <span>获取位置</span>
              </button> -->
              <!-- <button class="control-btn" @click="simulateLocationUpdate()">
                <span>模拟位置</span>
              </button> -->

              <button class="control-btn" @click="headlightsOn()" :disabled="!isConnected">
                <span>车灯</span>
              </button>
              <!-- <button class="control-btn" @click="sendCommand('line_follow')" :disabled="!isConnected">
                <span>开始循线</span>
              </button>
              <button class="control-btn" @click="sendCommand('line_stop')" :disabled="!isConnected">
                <span>停止循线</span>
              </button> -->
              <button class="control-btn" @click="sendCommand('take_photo')" :disabled="!isConnected">
                <span>拍照</span>
              </button>
              <button class="control-btn" @click="sendCommand('take_vedio')" :disabled="!isConnected">
                <span>录制</span>
              </button>
              <button class="control-btn" @click="sendCommand('stop_vedio')" :disabled="!isConnected">
                <span>停止录制</span>
              </button>
              
              <!-- 华为云IoT控制区域
              <div class="iot-controls-section">
                <h4 class="group-title">华为云IoT平台</h4>
                <div class="iot-status" :class="{ connected: iotConnected, disconnected: !iotConnected }">
                  <span class="iot-status-dot"></span>
                  <span>{{ iotConnected ? '已连接' : '未连接' }}</span>
                </div>
                
                <button 
                  class="control-btn iot-btn" 
                  @click="connectToHuaweiIoT()" 
                  :disabled="iotLoading || iotConnected"
                  :class="{ loading: iotLoading }"
                >
                  <span v-if="iotLoading">连接中...</span>
                  <span v-else-if="iotConnected">✅ 已连接</span>
                  <span v-else>🔗 连接IoT</span>
                </button>
          
                <button 
                  class="control-btn iot-btn disconnect" 
                  @click="disconnectFromHuaweiIoT()" 
                  :disabled="!iotConnected"
                >
                  <span>🔌 断开连接</span>
                </button>
                
                <!-- 产品信息显示 -->
                <!-- <div v-if="currentProduct" class="iot-product-info">
                  <div class="product-item">
                    <label>产品名称:</label>
                    <span>{{ currentProduct.name }}</span>
                  </div>
                  <div class="product-item">
                    <label>产品ID:</label>
                    <span>{{ currentProduct.product_id || currentProduct.app_id }}</span>
                  </div>
                  <div class="product-item">
                    <label>设备类型:</label>
                    <span>{{ currentProduct.device_type }}</span>
                  </div>
                </div>
              </div> -->
              <button class="control-btn" @click="sendCommand('m4')" :disabled="!isConnected">
                <span>排队</span>
              </button>
              <!-- <button class="control-btn" @click="sendCommand('')" :disabled="!isConnected">
                <span>雷达避障</span>
              </button>
              <button class="control-btn" @click="sendCommand('m7')" :disabled="!isConnected">
                <span>雷达跟踪</span>
              </button>
              <button class="control-btn" @click="sendCmd('m5')" :disabled="!isConnected">
                <span>雷达警卫</span>
              </button>
                <button class="control-btn" @click="sendCmd('m6')" :disabled="!isConnected">
                <span>关闭警卫</span>
              </button>
              <button class="control-btn" @click="sendCommand('')" :disabled="!isConnected">
                <span>版本信息</span>
              </button> -->
            </div>
          </div>
        </div>
      </div>
  </div>

    <!-- 底部日志区域 -->
    <div class="bottom-panel">
      <div class="log-section">
        <div class="log-container">
          <pre class="log-content">{{ log || '等待连接...' }}</pre>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { io } from 'socket.io-client'
import { ElMessage, ElNotification, ElMessageBox } from 'element-plus'
import BaiduMap from '../components/BaiduMap.vue'
import huaweiIoT from '../utils/huaweiIoT.js'

// 注册组件
const components = {
  BaiduMap
}

// 配置常量
const API_CONFIG = {
  SOCKET_URL: 'http://172.20.10.5:5000',  // 中间层Socket服务器
  CAR_API_URL: 'http://172.20.10.7:6500'  // 小车API服务器
}

const socket = io(API_CONFIG.SOCKET_URL)
const log = ref('')
const xSpeed = ref(0)
const ySpeed = ref(0)
const isConnected = ref(false)

// 轮盘控制相关变量
const joystickX = ref(0)
const joystickY = ref(0)
const isDragging = ref(false)
const joystickRadius = 65 // 轮盘半径
const deadZone = 10 // 死区半径

// 视频相关变量
const isVideoEnabled = ref(false)
const videoError = ref(false)
const videoErrorMessage = ref('')
const isVideoLoading = ref(false)
const videoResolution = ref('未知')
const videoElement = ref(null)

// 地图相关变量
const vehicleLocation = ref({
  latitude: null,
  longitude: null,
  address: ''
})
const mapComponent = ref(null)

// 华为云IoT状态
const iotConnected = ref(false)
const iotLoading = ref(false)
const deviceProducts = ref([])
const currentProduct = ref(null)
const authToken = ref(null)
const sensorData = ref(null) // 传感器数据

// 视频流URL - 基于Socket连接地址
const videoUrl = computed(() => {
  const timestamp = isVideoEnabled.value ? Date.now() : 0
  return `${API_CONFIG.CAR_API_URL}/video_feed?t=${timestamp}`
})

// 视频控制函数
function toggleVideo() {
  isVideoEnabled.value = !isVideoEnabled.value
  videoError.value = false
  videoErrorMessage.value = ''
  
  if (isVideoEnabled.value) {
    isVideoLoading.value = true
    log.value += `\n> [视频] 开启视频流: ${videoUrl.value}`
  } else {
    isVideoLoading.value = false
    log.value += `\n> [视频] 关闭视频流`
  }
}
function refreshVideo() {
  if (!isVideoEnabled.value) return
  videoError.value = false
  videoErrorMessage.value = ''
  isVideoLoading.value = true
  // 强制刷新视频流
  const img = videoElement.value
  if (img) {
    const newUrl = `${API_CONFIG.CAR_API_URL}/video_feed?t=${Date.now()}`
    img.src = newUrl
    log.value += `\n> [视频] 刷新视频流: ${newUrl}`
  }
}
function onVideoLoad() {
  isVideoLoading.value = false
  videoError.value = false
  // 获取视频分辨率
  const img = videoElement.value
  if (img) {
    videoResolution.value = `${img.naturalWidth}x${img.naturalHeight}`
    log.value += `\n> [视频] 视频流加载成功 - 分辨率: ${videoResolution.value}`
  }
}

function onVideoError(event) {
  isVideoLoading.value = false
  videoError.value = true
  
  const errorMessages = {
    'network': '网络连接失败，请检查小车是否在线',
    'decode': '视频解码失败，可能是格式不支持',
    'abort': '视频加载被中断',
    'unknown': '未知错误，请稍后重试'
  }
  
  // 根据错误类型设置消息
  const errorType = event.target?.error?.code || 'unknown'
  videoErrorMessage.value = errorMessages[errorType] || errorMessages.unknown
  
  log.value += `\n> [视频] 视频流加载失败: ${videoErrorMessage.value}`
  ElMessage.error(`视频加载失败: ${videoErrorMessage.value}`)
}
//ros2命令发送函数（雷达）
function sendCmd(cmdKey) {
      fetch(`${API_CONFIG.CAR_API_URL}/api/ros2/execute`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ cmd_key: cmdKey })
      })
      .then(res => res.json().then(data => ({status: res.status, body: data})))
    }

// 蜂鸣器控制函数
function beepControl(duration = 200) {
  const url = `${API_CONFIG.CAR_API_URL}/api/beep/${duration}`
  log.value += `\n> [蜂鸣器] 发送蜂鸣指令: ${duration}ms`
  fetch(url, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json'
    }
  })
  .then(response => {
    if (response.ok) {
      return response.text()
    } else {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
  })
  .then(result => {
    log.value += `\n> [蜂鸣器] 执行成功: ${result}`
    ElMessage.success(`蜂鸣器执行成功: ${duration}ms`)
  })
  .catch(error => {
    log.value += `\n> [蜂鸣器] 执行失败: ${error.message}`
    ElMessage.error(`蜂鸣器执行失败: ${error.message}`)
  })
}

// 紧急停止并重置功能
function emergencyReset() {
  const url = `${API_CONFIG.CAR_API_URL}/api/emergency_reset`
  log.value += `\n> [紧急重置] 执行紧急停止并重置...`
  
  // 显示确认对话框
  ElMessageBox.confirm(
    '确定要执行紧急停止并重置吗？这将立即停止小车所有运动并重置状态。',
    '紧急重置确认',
    {
      confirmButtonText: '立即执行',
      cancelButtonText: '取消',
      type: 'warning',
      confirmButtonClass: 'emergency-confirm-btn'
    }
  ).then(() => {
    // 用户确认，执行紧急重置
    fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    .then(response => {
      if (response.ok) {
        return response.json()
      } else {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`)
      }
    })
    .then(result => {
      log.value += `\n> [紧急重置] 执行成功: ${result.message}`
      log.value += `\n> [紧急重置] 执行操作: ${result.actions?.join(', ')}`
      
      ElNotification({
        title: '紧急重置成功',
        message: `${result.message}\n执行操作: ${result.actions?.join(', ')}`,
        type: 'success',
        duration: 5000
      })
      
      // 重置本地状态
      joystickX.value = 0
      joystickY.value = 0
      xSpeed.value = 0
      ySpeed.value = 0
    })
    .catch(error => {
      log.value += `\n> [紧急重置] 执行失败: ${error.message}`
      ElMessage.error(`紧急重置失败: ${error.message}`)
      ElNotification({
        title: '紧急重置失败',
        message: `执行紧急重置时发生错误: ${error.message}`,
        type: 'error',
        duration: 0
      })
    })
  }).catch(() => {
    log.value += `\n> [紧急重置] 用户取消操作`
    ElMessage.info('已取消紧急重置')
  })
}

function toggleFullscreen() {
  const img = videoElement.value
  if (!img || videoError.value) return
  
  if (document.fullscreenElement) {
    document.exitFullscreen()
  } else {
    img.requestFullscreen().catch(err => {
      console.log('无法进入全屏模式:', err)
      ElMessage.warning('无法进入全屏模式')
    })
  }
}

// 轮盘拖拽控制
function startDrag(event) {
  if (!isConnected.value) return
  
  isDragging.value = true
  event.preventDefault()
  
  const handleMove = (e) => {
    if (!isDragging.value) return
    
    const container = e.currentTarget?.closest('.joystick-background') || 
                     document.querySelector('.joystick-background')
    if (!container) return
    
    const rect = container.getBoundingClientRect()
    const centerX = rect.left + rect.width / 2
    const centerY = rect.top + rect.height / 2
    
    const clientX = e.touches ? e.touches[0].clientX : e.clientX
    const clientY = e.touches ? e.touches[0].clientY : e.clientY
    
    let deltaX = clientX - centerX
    let deltaY = clientY - centerY
    
    // 限制在圆形范围内
    const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY)
    if (distance > joystickRadius) {
      deltaX = (deltaX / distance) * joystickRadius
      deltaY = (deltaY / distance) * joystickRadius
    }
    
    joystickX.value = deltaX
    joystickY.value = deltaY
    
    // 发送控制命令
    sendJoystickCommand(deltaX, deltaY)
  }
  
  const handleEnd = () => {
    isDragging.value = false
    joystickX.value = 0
    joystickY.value = 0
    // 停止移动
    sendCommand('car_control', { dir: 0 })
    
    document.removeEventListener('mousemove', handleMove)
    document.removeEventListener('mouseup', handleEnd)
    document.removeEventListener('touchmove', handleMove)
    document.removeEventListener('touchend', handleEnd)
  }
  
  document.addEventListener('mousemove', handleMove)
  document.addEventListener('mouseup', handleEnd)
  document.addEventListener('touchmove', handleMove)
  document.addEventListener('touchend', handleEnd)
}

// 大灯控制相关变量
const headlightsStatus = ref(false) // 大灯开关状态

// 大灯控制函数
function headlightsOn() {
  const url = `${API_CONFIG.SOCKET_URL}/api/light_show/start_all`
  
  fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    //  body: JSON.stringify({
    //   cars: ["all"]  // 后端需要的参数格式
    // })
    // params: {
    //   effect: 1,// 传递持续时间参数
    //   speed: 100 // 传递速度参数
    // }
  })
  .then(response => {
    if (response.ok) {
      return response.json()
    } else {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
  })
  .then(result => {
    headlightsStatus.value = true
    log.value += `\n> [大灯] 执行成功: ${result.message}`
    ElMessage.success(`大灯控制成功: ${result.message}`)
    
    // 如果有持续时间，在指定时间后自动更新状态
    if (duration > 0) {
      setTimeout(() => {
        headlightsStatus.value = false
        log.value += `\n> [大灯] 自动关闭 (${duration}ms后)`
      }, duration)
    }
  })
  .catch(error => {
    log.value += `\n> [大灯] 执行失败: ${error.message}`
    ElMessage.error(`大灯控制失败: ${error.message}`)
  })
}
// 根据轮盘位置发送控制命令
function sendJoystickCommand(x, y) {
  const distance = Math.sqrt(x * x + y * y)
  
  // 死区检测
  if (distance < deadZone) {
    sendCommand('car_control', { dir: 0 }) // 停车
    return
  }
  
  // 计算角度 (0度为向上，顺时针)
  let angle = Math.atan2(x, -y) * (180 / Math.PI)
  if (angle < 0) angle += 360
  
  // 根据角度确定方向
  let direction = 0
  if (angle >= 315 || angle < 45) {
    direction = 1 // 前进
  } else if (angle >= 45 && angle < 135) {
    direction = 4 // 右移
  } else if (angle >= 135 && angle < 225) {
    direction = 2 // 后退
  } else if (angle >= 225 && angle < 315) {
    direction = 3 // 左移
  }
  
  // 发送命令和速度控制
  sendCommand('car_control', { dir: direction })
  
  // 可选：根据距离调节速度
  const speedFactor = Math.min(distance / joystickRadius, 1)
  const adjustedSpeed = Math.round(speedFactor * 127)
  
  if (adjustedSpeed > 20) { // 最小速度阈值
    sendCommand('speed_control', { 
      x: Math.round((x / joystickRadius) * 127), 
      y: Math.round((-y / joystickRadius) * 127) 
    })
  }
}

function sendCommand(cmd, params = {}) {
  if (!isConnected.value) {
    ElMessage.error('Socket连接已断开，无法发送命令')
    return
  }
  
  const commandId = Date.now() + Math.random() // 生成唯一ID
  const timeoutDuration = 5000 // 5秒超时
  
  log.value += `\n> [发送命令] ${cmd} ${JSON.stringify(params)} (ID: ${commandId})`
  
  // 带确认的emit，设置超时
  socket.timeout(timeoutDuration).emit('command', { cmd, params, id: commandId }, (error, response) => {
    if (error) {
      log.value += `\n> [错误] 命令超时或失败: ${cmd} (${error.message})`
      ElMessage.error(`命令发送失败: ${cmd} - ${error.message}`)
    } else {
      log.value += `\n> [确认] 命令已接收: ${cmd} - ${response?.status || 'OK'}`
    }
  })
  
  // 备用：监听特定响应（如果服务器不支持回调确认）
  const timeoutTimer = setTimeout(() => {
    log.value += `\n> [警告] 命令可能未收到响应: ${cmd} (${timeoutDuration/1000}秒超时)`
    ElMessage.warning(`命令响应超时: ${cmd}`)
  }, timeoutDuration)
  
  // 如果收到任何响应，清除警告定时器
  const responseHandler = (res) => {
    if (res.includes(cmd) || res.includes(commandId)) {
      clearTimeout(timeoutTimer)
      socket.off('response', responseHandler) // 移除临时监听器
    }
  }
  socket.on('response', responseHandler)
}

onMounted(() => {
  // 连接成功
  socket.on('connect', () => {
    isConnected.value = true
    log.value += `\n> [系统] Socket连接成功`
    ElNotification({
      title: '连接成功',
      message: '小车控制面板已连接',
      type: 'success',
      duration: 3000
    })
  })

  // 连接断开
  socket.on('disconnect', () => {
    isConnected.value = false
    log.value += `\n> [系统] Socket连接断开`
    ElNotification({
      title: '连接断开',
      message: '与小车的连接已断开，请检查网络',
      type: 'warning',
      duration: 5000
    })
  })

  // 连接错误
  socket.on('connect_error', (error) => {
    isConnected.value = false
    log.value += `\n> [错误] 连接失败: ${error.message}`
    
  })

  // 重连尝试
  socket.on('reconnect_attempt', (attemptNumber) => {
    log.value += `\n> [系统] 尝试重连 (${attemptNumber})`
    ElMessage.info(`正在尝试重连... (${attemptNumber})`)
  })

  // 重连成功
  socket.on('reconnect', (attemptNumber) => {
    isConnected.value = true
    log.value += `\n> [系统] 重连成功 (尝试${attemptNumber}次)`
    ElNotification({
      title: '重连成功',
      message: `经过${attemptNumber}次尝试，已重新连接到小车`,
      type: 'success',
      duration: 3000
    })
  })

  // 重连失败
  socket.on('reconnect_failed', () => {
    isConnected.value = false
    log.value += `\n> [错误] 重连失败，请检查网络连接`
    ElNotification({
      title: '重连失败',
      message: '无法重新连接到小车，请检查网络设置',
      type: 'error',
      duration: 0
    })
  })

  // 接收小车响应
  socket.on('response', (res) => {
    log.value += `\n> [小车回应] ${res}`
  })
})

// // 地图相关方法
// function onLocationUpdate(location) {
//   vehicleLocation.value = {
//     latitude: location.lat,
//     longitude: location.lng,
//     address: location.address || ''
//   }
//   log.value += `\n> [位置] 位置更新: ${location.lat.toFixed(6)}, ${location.lng.toFixed(6)}`
// }

// function onMapReady(mapInstance) {
//   log.value += `\n> [地图] 百度地图初始化完成`
//   ElMessage.success('地图已就绪')
// }

// // 更新小车位置（从后端API获取）
// async function updateVehicleLocation() {
//   try {
//     const response = await fetch(`${API_CONFIG.SOCKET_URL}/api/location`, {
//       method: 'GET',
//       headers: {
//         'Content-Type': 'application/json'
//       }
//     })
    
//     if (response.ok) {
//       const locationData = await response.json()
//       if (locationData.latitude && locationData.longitude) {
//         // 更新地图上的位置
//         if (mapComponent.value) {
//           mapComponent.value.updateLocation(
//             locationData.latitude, 
//             locationData.longitude,
//             locationData.address
//           )
//         }
//         log.value += `\n> [位置] 从API获取位置成功`
//       }
//     } else {
//       throw new Error(`HTTP ${response.status}`)
//     }
//   } catch (error) {
//     log.value += `\n> [位置] 获取位置失败: ${error.message}`
//     console.error('获取位置失败:', error)
//   }
// }

// // 模拟位置数据（用于测试）
// function simulateLocationUpdate() {
//   // 模拟北京地区的随机位置
//   const baseLat = 39.9042
//   const baseLng = 116.4074
//   const randomLat = baseLat + (Math.random() - 0.5) * 0.01
//   const randomLng = baseLng + (Math.random() - 0.5) * 0.01
  
//   if (mapComponent.value) {
//     mapComponent.value.updateLocation(randomLat, randomLng, '模拟位置')
//   }
// }

// 华为云IoT集成功能
async function connectToHuaweiIoT() {
  iotLoading.value = true
  log.value += `\n> [华为云IoT] 开始连接华为云IoT平台...`
  
  try {
    // 获取认证令牌
    const token = await huaweiIoT.getAuthToken()
    authToken.value = token
    iotConnected.value = true
    // 获取产品列表
    await refreshDeviceProducts()
  } catch (error) {
    iotConnected.value = false
    authToken.value = null
    log.value += `\n> [华为云IoT] 连接失败: ${error.message}`
  } finally {
    iotLoading.value = false
  }
}

async function refreshDeviceProducts() {
  if (!authToken.value) {
    ElMessage.warning('请先连接华为云IoT平台')
    return
  }
  
  try {
    log.value += `\n> [华为云IoT] 获取设备产品列表...`
    
    // 这里可以调用华为云IoT API获取产品列表
    // 目前作为示例，我们创建一个智能车产品
    const productData = {
      app_id: 'smartcar_app',
      name: '智能小车控制系统',
      device_type: 'SmartCar',
      protocol_type: 'MQTT',
      data_format: 'json',
      description: '基于华为云IoT的智能小车远程控制系统'
    }
    
    const product = await huaweiIoT.createProduct(productData, authToken.value)
    deviceProducts.value = [product]
    currentProduct.value = product
    
    log.value += `\n> [华为云IoT] 产品创建/获取成功: ${product.name}`
    ElMessage.success(`产品 "${product.name}" 已就绪`)
    
  } catch (error) {
    log.value += `\n> [华为云IoT] 获取产品列表失败: ${error.message}`
    ElMessage.error(`获取产品列表失败: ${error.message}`)
  }
}

async function createSmartCarDevice(deviceName = '智能小车_001') {
  if (!authToken.value || !currentProduct.value) {
    ElMessage.warning('请先连接华为云IoT平台并选择产品')
    return
  }
  
  try {
    log.value += `\n> [华为云IoT] 创建设备: ${deviceName}...`
    
    // 这里可以调用华为云IoT API创建设备
    const deviceData = {
      product_id: currentProduct.value.product_id,
      device_name: deviceName,
      node_id: `smartcar_${Date.now()}`,
      description: `智能小车设备 - ${deviceName}`,
      device_info: {
        location: vehicleLocation.value,
        car_status: 'online',
        video_enabled: isVideoEnabled.value
      }
    }
    
    // 模拟设备创建成功
    const device = {
      device_id: `device_${Date.now()}`,
      device_name: deviceName,
      product_id: currentProduct.value.product_id,
      status: 'ONLINE',
      created_time: new Date().toISOString(),
      ...deviceData
    }
    
    log.value += `\n> [华为云IoT] 设备创建成功: ${device.device_id}`
    ElNotification({
      title: '设备创建成功',
      message: `设备 "${deviceName}" 已成功注册到华为云IoT平台`,
      type: 'success',
      duration: 5000
    })
    
    return device
    
  } catch (error) {
    log.value += `\n> [华为云IoT] 设备创建失败: ${error.message}`
    ElMessage.error(`设备创建失败: ${error.message}`)
    throw error
  }
}

function disconnectFromHuaweiIoT() {
  iotConnected.value = false
  authToken.value = null
  deviceProducts.value = []
  currentProduct.value = null
  
  log.value += `\n> [华为云IoT] 已断开华为云IoT连接`
  ElMessage.info('已断开华为云IoT连接')
}

// 设备属性查询相关变量
const currentDeviceId = ref('') // 当前设备ID
const deviceProperties = ref({}) // 设备属性数据
const isQueryingProperties = ref(false) // 查询状态

/**
 * 查询设备属性
 */
async function queryDeviceProperties(serviceId = null) {
  if (!iotConnected.value) {
    ElMessage.warning('请先连接华为云IoT平台')
    return
  }
  
  if (!currentDeviceId.value) {
    ElMessage.warning('请先输入设备ID或创建设备')
    return
  }
  
  isQueryingProperties.value = true
  log.value += `\n> [华为云IoT] 查询设备属性: ${currentDeviceId.value}${serviceId ? `, 服务: ${serviceId}` : ''}`
  
  try {
    const result = await huaweiIoT.queryDeviceProperties(currentDeviceId.value, serviceId)
    
    if (result.success) {
      deviceProperties.value = result.data
      log.value += `\n> [华为云IoT] 属性查询成功，请求ID: ${result.requestId}`
      
      ElNotification({
        title: '设备属性查询成功',
        message: `已获取设备 "${currentDeviceId.value}" 的属性信息`,
        type: 'success',
        duration: 3000
      })
      
      // 显示属性信息
      if (result.data?.response?.services) {
        const services = Array.isArray(result.data.response.services) 
          ? result.data.response.services 
          : [result.data.response.services]
        
        services.forEach(service => {
          log.value += `\n> [设备属性] 服务: ${service.serviceId}, 时间: ${service.eventTime}`
          Object.entries(service.properties || {}).forEach(([key, value]) => {
            log.value += `\n>   ${key}: ${value}`
          })
        })
      }
      
      return result
    } else {
      throw new Error(result.error)
    }
  } catch (error) {
    log.value += `\n> [华为云IoT] 属性查询失败: ${error.message}`
    ElMessage.error(`设备属性查询失败: ${error.message}`)
  } finally {
    isQueryingProperties.value = false
  }
}

// 华为云IoT相关函数
function toggleIoTConnection() {
  if (iotConnected.value) {
    disconnectIoT()
  } else {
    connectIoT()
  }
}

async function connectIoT() {
  iotLoading.value = true
  log.value += '\n> [华为云IoT] 开始连接...'
  
  try {
    await huaweiIoT.connectAndSubscribe((data) => {
      sensorData.value = data
      log.value += `\n> [华为云IoT] 接收数据: 温度${data.temperature}°C, 照度${data.illumination}lux`
    })
    
    iotConnected.value = true
    iotLoading.value = false
    
    ElNotification({
      title: '华为云IoT连接成功',
      message: '已开始接收传感器数据',
      type: 'success',
      duration: 3000
    })
    
    log.value += '\n> [华为云IoT] 连接成功，开始接收数据'
  } catch (error) {
    iotLoading.value = false
    log.value += `\n> [华为云IoT] 连接失败: ${error.message}`
    ElMessage.error(`华为云IoT连接失败: ${error.message}`)
  }
}

function disconnectIoT() {
  try {
    huaweiIoT.disconnect()
    iotConnected.value = false
    sensorData.value = null
    
    ElMessage.success('华为云IoT已断开连接')
    log.value += '\n> [华为云IoT] 已断开连接'
  } catch (error) {
    log.value += `\n> [华为云IoT] 断开连接失败: ${error.message}`
    ElMessage.error(`断开连接失败: ${error.message}`)
  }
}

function formatTime(timeString) {
  if (!timeString) return '未知'
  
  try {
    const date = new Date(timeString)
    return date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (error) {
    return '格式错误'
  }
}

</script>

<style scoped>
.layout{
  display: flex;
  flex-direction: column;
}
.container {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  padding: 1rem;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  position: relative;
  overflow-x: hidden;
}

/* 右上角连接状态 */
.connection-status-corner {
  position: fixed;
  top: 1rem;
  right: 1rem;
  z-index: 1000;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1rem;
  border-radius: 25px;
  font-size: 0.9rem;
  font-weight: 600;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.connection-status-corner.connected {
  background: rgba(72, 187, 120, 0.9);
  color: white;
  border: 2px solid rgba(72, 187, 120, 0.5);
}

.connection-status-corner.disconnected {
  background: rgba(245, 101, 101, 0.9);
  color: white;
  border: 2px solid rgba(245, 101, 101, 0.5);
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: currentColor;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; transform: scale(1); }
  50% { opacity: 0.7; transform: scale(1.1); }
}

/* 主要布局 */
.main-layout {
  display: grid;
  grid-template-columns: 1fr 400px;
  gap: 1rem;
  margin-bottom: 1rem;
  height: calc(100vh - 200px);
}

/* 左侧面板 - 视频区域 */
.left-panel {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.video-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  padding: 1rem;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  height: 75vh;
  display: flex;
  flex-direction: column;
  width: 50vw;
}

/* 地图区域样式 */
.map-section-wrapper {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  flex: 1;
  min-height: 300px;
  display: flex;
  flex-direction: column;
}

/* 右侧面板 - 控制区域 */
.right-panel {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  max-height: 70vh;
}

.control-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  padding: 1rem;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.joystick-section {
  flex: 0 0 auto;
}

.buttons-section {
  flex: 1;
  margin-left: 1rem;
  margin-top: 5rem;
  display: flex;
  flex-direction: column;
}

.xycontrol-section {
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 底部面板 - 日志区域 */
.bottom-panel {
  backdrop-filter: blur(10px);
  border-radius: 15px;
  padding: 1rem;
  height: 150px;
}

.log-section {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 通用区域头部 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
  padding-bottom: 0.75rem;
  border-bottom: 2px solid #e2e8f0;
}

.section-header h3 {
  font-size: 1.1rem;
  font-weight: 700;
  margin: 0;
  color: #2d3748;
}

/* 视频控制 */
.video-controls {
  display: flex;
  gap: 0.5rem;
}

.video-control-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 8px;
  font-size: 0.8rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  background: linear-gradient(135deg, #718096, #4a5568);
  color: white;
}

.video-control-btn.active {
  background: linear-gradient(135deg, #48bb78, #38a169);
}

.video-control-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.video-container {
  flex: 1;
  background: #000;
  border-radius: 10px;
  overflow: hidden;
  min-height: 300px;
  max-height: 75vh;
  max-width: 50vw;
  position: relative;
}

.video-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: linear-gradient(135deg, #2d3748, #1a202c);
  color: white;
}

.placeholder-content {
  text-align: center;
}

.placeholder-text {
  font-size: 1rem;
  font-weight: 600;
}

.video-stream-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
}

.video-stream {
  width: 100%;
  height: 100%;
  object-fit: contain;
  cursor: pointer;
}

.video-error, .video-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(26, 32, 44, 0.9);
  color: white;
  text-align: center;
}

.loading-spinner {
  width: 30px;
  height: 30px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-top: 3px solid #4299e1;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 1rem;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.video-info {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 20px;
  font-size: 0.8rem;
  display: flex;
  gap: 1rem;
}

.retry-btn {
  background: linear-gradient(135deg, #4299e1, #3182ce);
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 8px;
  cursor: pointer;
  margin-top: 1rem;
}

/* 轮盘控制 */
.joystick-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.75rem;
}

.joystick-background {
  position: relative;
  width: 180px;
  height: 180px;
  border-radius: 50%;
  background: linear-gradient(135deg, #f7fafc, #edf2f7);
  border: 4px solid #e2e8f0;
  box-shadow: 
    inset 0 4px 8px rgba(0, 0, 0, 0.1),
    0 4px 16px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  user-select: none;
}

.joystick-center {
  position: absolute;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #718096;
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.3);
}

.joystick-handle {
  position: absolute;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: 3px solid white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  cursor: grab;
  transition: all 0.1s ease;
  z-index: 10;
}

.joystick-handle:active {
  cursor: grabbing;
  transform: scale(1.1) !important;
}

.direction-indicators {
  position: absolute;
  width: 100%;
  height: 100%;
}

.indicator {
  position: absolute;
  font-size: 1.2rem;
  opacity: 0.6;
  transition: all 0.3s ease;
  border: none;
  background: none;
  cursor: pointer;
  outline: none;
  padding: 0.25rem;
}

.indicator.up {
  top: 10px;
  left: 50%;
  transform: translateX(-50%);
}

.indicator.down {
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
}

.indicator.left {
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
}

.indicator.right {
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
}

.indicator:hover {
  opacity: 1;
}

.joystick-info {
  font-family: 'Courier New', monospace;
  font-size: 0.8rem;
  color: #718096;
  background: rgba(255, 255, 255, 0.8);
  padding: 0.5rem 1rem;
  border-radius: 15px;
  border: 1px solid #e2e8f0;
}

/* 按钮网格 */
.button-grid {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.button-group {
  display: flex;
  gap: 0.5rem;
  justify-content: center;
  flex-wrap: wrap;
  align-items: center;
}

.control-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.25rem;
  padding: 0.75rem 0.5rem;
  border: none;
  border-radius: 10px;
  font-size: 0.8rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  text-align: center;
  min-height: 60px;
}

.control-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}

.control-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none !important;
}


/* 速度控制组 */
.speed-control-group {
  margin-top: 1rem;
  padding-top: 0.5rem;
}

.speed-item {
  margin-bottom: 0.75rem;
}

.speed-item label {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
  font-weight: 600;
  font-size: 0.9rem;
}

.speed-value {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  padding: 0.25rem 0.5rem;
  border-radius: 15px;
  font-size: 0.8rem;
  min-width: 40px;
  text-align: center;
}

.speed-slider {
  width: 100%;
  height: 6px;
  border-radius: 3px;
  background: #e2e8f0;
  outline: none;
  appearance: none;
  cursor: pointer;
}

.speed-slider::-webkit-slider-thumb {
  appearance: none;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea, #764ba2);
  cursor: pointer;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
}

/* 日志区域 */
.log-container {
  flex: 1;
  background: #1a202c;
  border-radius: 10px;
  padding: 0.75rem;
  overflow-y: auto;
  border: 1px solid #2d3748;
}

.log-content {
  color: #e2e8f0;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 0.8rem;
  line-height: 1.4;
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}

/* 华为云IoT控制样式 */
.iot-controls-section {
  margin-top: 1rem;
  padding: 1rem;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 15px;
  border: 2px solid #e2e8f0;
  backdrop-filter: blur(10px);
}

.group-title {
  margin: 0 0 1rem 0;
  font-size: 1rem;
  font-weight: 700;
  color: #2d3748;
  text-align: center;
  border-bottom: 2px solid #667eea;
  padding-bottom: 0.5rem;
}

.iot-status {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 1rem;
  padding: 0.5rem 1rem;
  border-radius: 10px;
  font-weight: 600;
  font-size: 0.9rem;
  transition: all 0.3s ease;
}

.iot-status.connected {
  background: linear-gradient(135deg, #48bb78, #38a169);
  color: white;
}

.iot-status.disconnected {
  background: linear-gradient(135deg, #fc8181, #e53e3e);
  color: white;
}

.iot-status-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: currentColor;
  animation: pulse 2s infinite;
}

.iot-btn {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  margin: 0.25rem;
  font-size: 0.8rem;
  min-width: 120px;
}

.iot-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #5a67d8, #6b46c1);
}

.iot-btn.loading {
  background: linear-gradient(135deg, #a0aec0, #718096);
  animation: pulse 1.5s infinite;
}

.iot-btn.disconnect {
  background: linear-gradient(135deg, #fc8181, #e53e3e);
}

.iot-btn.disconnect:hover:not(:disabled) {
  background: linear-gradient(135deg, #f56565, #e53e3e);
}

.iot-product-info {
  margin-top: 1rem;
  padding: 1rem;
  background: rgba(102, 126, 234, 0.1);
  border-radius: 10px;
  border: 1px solid rgba(102, 126, 234, 0.3);
}

.product-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
  font-size: 0.8rem;
}

.product-item:last-child {
  margin-bottom: 0;
}

.product-item label {
  font-weight: 600;
  color: #4a5568;
  min-width: 80px;
}

.product-item span {
  font-family: 'Courier New', monospace;
  background: rgba(255, 255, 255, 0.8);
  padding: 0.25rem 0.5rem;
  border-radius: 5px;
  color: #2d3748;
  border: 1px solid #e2e8f0;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.sensor-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 0.75rem;
  margin-bottom: 1rem;
}

.sensor-item {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 10px;
  padding: 0.75rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.sensor-label {
  display: block;
  font-size: 0.9rem;
  font-weight: 600;
  margin-bottom: 0.25rem;
  color: #2d3748;
}

.sensor-value {
  font-size: 1.2rem;
  font-weight: 700;
  color: #2b6cb0;
}

/* 状态消息 */
.status-message {
  font-size: 0.9rem;
  color: #718096;
  text-align: center;
  margin: 1rem 0;
}

/* 加载指示器 */
.loading-icon {
  animation: spin 1s linear infinite;
  font-size: 1.2rem;
  margin-right: 0.5rem;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 华为云IoT状态面板 */
.iot-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 1.5rem;
  margin-bottom: 1rem;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.iot-connect-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  padding: 0.75rem 1.5rem;
  font-size: 0.9rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.iot-connect-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.iot-connect-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.iot-connect-btn.connected {
  background: linear-gradient(135deg, #48bb78 0%, #38a169 100%);
}

.iot-connect-btn.loading {
  background: linear-gradient(135deg, #ed8936 0%, #dd6b20 100%);
}

.iot-data {
  margin-top: 1rem;
}

.iot-info {
  text-align: center;
  margin-top: 0.75rem;
  font-size: 0.8rem;
  color: #718096;
}

.sensor-value.warning {
  color: #ed8936;
}

.sensor-value.alert {
  color: #e53e3e;
  font-weight: 800;
}
</style>
